using MediatR;
using Microsoft.Data.SqlClient;
using PiggyBankCashFlowApi.Delegate.command;
using PiggyBankCashFlowApi.Exception;
using PiggyBankCashFlowApi.Ext;
using PiggyBankCashFlowApi.Repo;
using PiggyBankCashFlowApi.Repo.Entity;

namespace PiggyBankCashFlowApi.Delegate.Handler;

public class CreateCashFlowHandler(CashFlowRepo repo,IHttpContextAccessor accessor, ILogger<CreateCashFlowHandler> logger):IRequestHandler<CreateCashFlowCommand,CashFlowEntity>
{
    public async Task<CashFlowEntity> Handle(CreateCashFlowCommand command, CancellationToken cancellationToken)
    {
        var userId = accessor.GetUserId();
        
        if (!userId.Equals(command.UserId.ToString()))
        {
            throw new ForbiddenException($"Cannot create cash flow for other user. User Id:{userId} vs Cash flow userId:{command.UserId}");
        }

        var id = await repo.CreateCashFlowAsync(
            command.UserId,command.Subject,command.Amount,
            command.Direction,command.Comment,command.PicUrl,command.TransferDate);
        if (id < 0)
        {
            throw new DbOpNotAcceptedException("Cannot create cash flow: Opt Not Accepted");
        }
        else
        {
            return new CashFlowEntity()
            {
                Id = id,
                UserId = command.UserId,
                Subject = command.Subject,
                Amount = command.Amount,
                Direction = command.Direction,
                Comment = command.Comment,
                PicUrl = command.PicUrl,
                TransferDate = DateTimeOffset.FromUnixTimeMilliseconds(command.TransferDate).UtcDateTime
            };
        }
    }
}